package cn.iocoder.yudao.module.tms.service.companyaccountperiod;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import cn.iocoder.yudao.module.tms.controller.admin.companyaccountperiod.vo.*;
import cn.iocoder.yudao.module.tms.dal.dataobject.companyaccountperiod.CompanyAccountPeriodDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.tms.dal.mysql.companyaccountperiod.CompanyAccountPeriodMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.tms.enums.ErrorCodeConstants.*;

/**
 * 公司账期信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class CompanyAccountPeriodServiceImpl implements CompanyAccountPeriodService {

    @Resource
    private CompanyAccountPeriodMapper companyAccountPeriodMapper;

    @Override
    public Long createCompanyAccountPeriod(CompanyAccountPeriodSaveReqVO createReqVO) {
        // 校验公司是否已存在账期配置
        CompanyAccountPeriodDO existingPeriod = companyAccountPeriodMapper.selectByCompanyId(createReqVO.getCompanyId());
        if (existingPeriod != null) {
            throw exception(COMPANY_ACCOUNT_PERIOD_EXISTS);
        }

        // 插入
        CompanyAccountPeriodDO companyAccountPeriod = BeanUtils.toBean(createReqVO, CompanyAccountPeriodDO.class);
        
        // 如果没有设置当前合作金额，默认为0
        if (companyAccountPeriod.getCurrentCreditUsed() == null) {
            companyAccountPeriod.setCurrentCreditUsed(BigDecimal.ZERO);
        }
        
        companyAccountPeriodMapper.insert(companyAccountPeriod);

        // 返回
        return companyAccountPeriod.getId();
    }

    @Override
    public void updateCompanyAccountPeriod(CompanyAccountPeriodSaveReqVO updateReqVO) {
        // 校验存在
        validateCompanyAccountPeriodExists(updateReqVO.getId());
        
        // 更新
        CompanyAccountPeriodDO updateObj = BeanUtils.toBean(updateReqVO, CompanyAccountPeriodDO.class);
        companyAccountPeriodMapper.updateById(updateObj);
    }

    @Override
    public void deleteCompanyAccountPeriod(Long id) {
        // 校验存在
        validateCompanyAccountPeriodExists(id);
        // 删除
        companyAccountPeriodMapper.deleteById(id);
    }

    @Override
    public void deleteCompanyAccountPeriodListByIds(List<Long> ids) {
        // 删除
        companyAccountPeriodMapper.deleteByIds(ids);
    }

    private void validateCompanyAccountPeriodExists(Long id) {
        if (companyAccountPeriodMapper.selectById(id) == null) {
            throw exception(COMPANY_ACCOUNT_PERIOD_NOT_EXISTS);
        }
    }

    @Override
    public CompanyAccountPeriodDO getCompanyAccountPeriod(Long id) {
        return companyAccountPeriodMapper.selectById(id);
    }

    @Override
    public CompanyAccountPeriodDO getCompanyAccountPeriodByCompanyId(Long companyId) {
        return companyAccountPeriodMapper.selectByCompanyId(companyId);
    }

    @Override
    public PageResult<CompanyAccountPeriodDO> getCompanyAccountPeriodPage(CompanyAccountPeriodPageReqVO pageReqVO) {
        return companyAccountPeriodMapper.selectPage(pageReqVO);
    }

    @Override
    public boolean checkCreditLimitAlert(Long companyId) {
        CompanyAccountPeriodDO period = companyAccountPeriodMapper.selectByCompanyId(companyId);
        if (period == null) {
            return false;
        }

        // 判断当前合作金额是否超过预警金额
        BigDecimal currentUsed = period.getCurrentCreditUsed();
        BigDecimal alertAmount = period.getCreditAlertAmount();
        
        if (currentUsed == null || alertAmount == null) {
            return false;
        }

        return currentUsed.compareTo(alertAmount) >= 0;
    }

    @Override
    public boolean checkBillingCycleAlert(Long companyId) {
        CompanyAccountPeriodDO period = companyAccountPeriodMapper.selectByCompanyId(companyId);
        if (period == null || period.getBillingDueDate() == null) {
            return false;
        }

        LocalDate dueDate = period.getBillingDueDate();
        LocalDate today = LocalDate.now();
        
        // 计算距离到期日的天数
        long daysUntilDue = ChronoUnit.DAYS.between(today, dueDate);
        
        // 如果剩余天数小于等于提醒天数，则需要提醒
        Integer alertDays = period.getBillingAlertDays();
        if (alertDays == null) {
            return false;
        }

        return daysUntilDue <= alertDays && daysUntilDue >= 0;
    }

}
